﻿using UnityEngine;
using UnityEditor;
using System.Text;
using System.Collections.Generic;

namespace MagicLib
{
    
    public class BatchRename : ScriptableWizard
    {
        private static bool isInitialized = false;
        private static BatchRename currentWindow = null;

        [MenuItem("MagicLib/BatchRename", priority = 12)]
        public static void ToggleWindow()
        {
            // 如果窗口存在且未关闭，则关闭它
            if (currentWindow != null)
            {
                currentWindow.Close();
                currentWindow = null;
                return;
            }

            // 否则创建新窗口
            CreateWindow();
        }

        public static void CreateWindow()
        {
            try
            {
                currentWindow = DisplayWizard<BatchRename>("批量重命名工具", "关闭", "重命名");
                if (currentWindow != null)
                {
                    currentWindow.maxSize = new Vector2(300, 240);
                    currentWindow.minSize = new Vector2(100, 240);
                }

                // 初始化一次性事件
                if (!isInitialized)
                {
                    EditorApplication.update += InitializeOnce;
                    EditorApplication.quitting += () =>
                    {
                        isInitialized = false;
                        EditorApplication.update -= InitializeOnce;
                    };
                    isInitialized = true;
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError($"脚本创建失败: {e}");
                currentWindow = null;
                isInitialized = false;
                EditorApplication.update -= InitializeOnce;
                throw;
            }
        }

        // 初始化事件，只在第一次运行时调用一次
        private static void InitializeOnce()
        {
            // 确保只初始化一次
            EditorApplication.update -= InitializeOnce;
            // 确保快捷键注册成功
            EditorApplication.delayCall += () =>
            {
                Menu.SetChecked("MagicLib/CreateComponentCode &x", false);
            };
        }

        [Header("命名参数配置")]
        [Tooltip("资源类型前缀 (如: 类名)")]
        public string prefix = "";

        [Tooltip("基础名称 (必填)")]
        public string baseName = "";

        [Tooltip("起始序号")]
        public int startID = 1;

        [Tooltip("序号位数 (如: 3=001, 4=0001)")]
        public int idDigits = 3;

        [Tooltip("资源后缀 (如: Variant, Type)")]
        public string suffix = "";


        private void OnWizardCreate() { } // 必须实现但不需要内容

        private void OnWizardOtherButton()
        {
            if (!ValidateInput()) return;

            // 创建撤销组
            Undo.RegisterCompleteObjectUndo(Selection.objects, "Batch Rename Assets");

            int currentID = startID;
            List<Object> renamedObjects = new List<Object>();
            List<string> originalNames = new List<string>();

            try
            {
                // 开始资源编辑批处理
                AssetDatabase.StartAssetEditing();

                foreach (var asset in Selection.objects)
                {
                    originalNames.Add(asset.name);
                    RenameAsset(asset, ref currentID);
                    renamedObjects.Add(asset);
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError($"重命名出错: {e.Message}\n{e.StackTrace}");
                errorString = "操作失败，请查看控制台";

                // 尝试恢复原始名称
                for (int i = 0; i < renamedObjects.Count; i++)
                {
                    RestoreOriginalName(renamedObjects[i], originalNames[i]);
                }
            }
            finally
            {
                // 结束资源编辑批处理
                AssetDatabase.StopAssetEditing();

                // 刷新资源数据库
                AssetDatabase.Refresh();

                // 强制重新导入所有修改的资源
                foreach (var asset in renamedObjects)
                {
                    string path = AssetDatabase.GetAssetPath(asset);
                    if (!string.IsNullOrEmpty(path))
                    {
                        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                    }
                }

                // 刷新编辑器界面
                EditorUtility.FocusProjectWindow();
                Selection.objects = renamedObjects.ToArray();

                // Debug.Log($"成功重命名 {renamedObjects.Count} 个资源");
            }
        }

        private void RestoreOriginalName(Object asset, string originalName)
        {
            string path = AssetDatabase.GetAssetPath(asset);
            if (!string.IsNullOrEmpty(path))
            {
                AssetDatabase.RenameAsset(path, originalName);
            }
            else if (asset is GameObject gameObject)
            {
                gameObject.name = originalName;
            }
        }

        private bool ValidateInput()
        {
            errorString = null;

            if (Selection.objects.Length == 0)
            {
                errorString = "请至少选择一个资源";
                return false;
            }

            if (string.IsNullOrWhiteSpace(baseName))
            {
                errorString = "基础名称不能为空";
                return false;
            }

            if (idDigits < 1 || idDigits > 6)
            {
                errorString = "序号位数需在1-6之间";
                return false;
            }

            return true;
        }

        private void OnWizardUpdate()
        {
            helpString = $"已选择 {Selection.objects.Length} 个资源";
            ValidateInput();
        }

        private void OnSelectionChange() => OnWizardUpdate();

        private void RenameAsset(Object asset, ref int currentID)
        {
            // 构建新名称
            string newName = BuildNewName(currentID);

            // 获取资源路径
            string path = AssetDatabase.GetAssetPath(asset);

            // 处理场景中的游戏对象
            if (string.IsNullOrEmpty(path) && asset is GameObject gameObject)
            {
                gameObject.name = newName;
                currentID++;
                return;
            }

            // 处理资源文件
            if (!string.IsNullOrEmpty(path))
            {
                // 使用更可靠的重命名方法
                string result = AssetDatabase.RenameAsset(path, newName);

                if (!string.IsNullOrEmpty(result))
                {
                    Debug.LogError($"重命名失败: {result} (资源: {asset.name}, 目标名称: {newName})");
                    errorString = "部分重命名失败";
                }
                else
                {
                    // 确保资源名称实际更新
                    AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                    currentID++;
                }
            }
            else
            {
                Debug.LogWarning($"无法重命名对象: {asset.name} (类型: {asset.GetType().Name})，仅支持资源和场景中的GameObject");
            }
        }

        private string BuildNewName(int currentID)
        {
            StringBuilder newName = new StringBuilder();

            // 添加前缀
            if (!string.IsNullOrWhiteSpace(prefix))
            {
                newName.Append(prefix.Trim());
                newName.Append("_");
            }

            // 添加基础名称
            newName.Append(baseName.Trim());

            // 添加序号
            newName.Append("_");
            newName.Append(currentID.ToString($"D{idDigits}"));

            // 添加后缀
            if (!string.IsNullOrWhiteSpace(suffix))
            {
                newName.Append("_");
                newName.Append(suffix.Trim());
            }

            return newName.ToString();
        }
    }
}